package service

import (
	"context"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"

	v1 "traceid-test/api/helloworld/v1"
	"traceid-test/internal/biz"

	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	"github.com/go-kratos/kratos/v2/transport/grpc"
	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"

	"github.com/go-kratos/kratos/v2/log"
)

// GreeterService is a greeter service.
type GreeterService struct {
	v1.UnimplementedGreeterServer

	uc  *biz.GreeterUsecase
	log *log.Helper
}

// NewGreeterService new a greeter service.
func NewGreeterService(uc *biz.GreeterUsecase, logger log.Logger) *GreeterService {
	return &GreeterService{
		uc:  uc,
		log: log.NewHelper(logger),
	}
}

// SayHello implements helloworld.GreeterServer.
func (s *GreeterService) SayHello(ctx context.Context, in *v1.HelloRequest) (*v1.HelloReply, error) {
	g, err := s.uc.CreateGreeter(ctx, &biz.Greeter{Hello: in.Name})
	if err != nil {
		return nil, err
	}
	log.Context(ctx).Info("这样子写info才有traceid")
	log.Info("这样子写info不会有traceid")
	s.log.Info("这样子写没有traceid，全局的log怎么打印？")
	s.log.WithContext(ctx).Info("这样子有traceid")
	//请求下个接口
	s.reqHttp(ctx)
	time.Sleep(1 * time.Second)
	s.reqGrpc(ctx)

	return &v1.HelloReply{Message: "Hello " + g.Hello}, nil
}

// http请求
func (s *GreeterService) reqHttp(ctx context.Context) {

	client := http.Client{Transport: otelhttp.NewTransport(http.DefaultTransport)}
	req, _ := http.NewRequestWithContext(ctx, "GET", "http://localhost:8001/helloworld/"+"test的http请求", nil)
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close() // 确保关闭响应体
	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	// 打印响应状态码和响应体
	fmt.Printf("Response Status: %s\n", resp.Status)
	fmt.Printf("Response Body: %s\n", body)
}

// grpc请求
func (s *GreeterService) reqGrpc(ctx context.Context) error {
	gconn, err := grpc.DialInsecure(ctx,
		grpc.WithEndpoint("localhost:9001"),
		grpc.WithMiddleware(
			recovery.Recovery(),
			tracing.Client(), //没有这个没办法传递
		),
		grpc.WithTimeout(2*time.Second),
		// for tracing remote ip recording
		// grpc.WithOptions(grpcx.WithStatsHandler(&tracing.ClientHandler{})),
	)
	if err != nil {
		return err
	}
	msg := v1.NewGreeterClient(gconn)
	msg.SayHello(ctx, &v1.HelloRequest{Name: "test的grpc请求"})
	return nil
}
